library(devtools)
source_url("https://gitee.com/ry2an/my_public_functions_r/raw/master/paste_vec.R")
source_url("https://gitee.com/ry2an/my_public_functions_r/raw/master/create_0_row_df.R")

date_count <- function(data = data.frame(), dates_name = c(), precise = 7){
  all_time <- c()
  for(i in 1:length(dates_name)){
    all_time <- c(all_time, data[,dates_name[i]])
  }
  all_time <- all_time[is.na(all_time) == F]
  all_time <- substr(all_time, 1, precise)
  all_time <- unique(all_time)
  out_names <- paste(dates_name,"_num", sep = "")
  
  
  for(i in 1:length(out_names)){
    order <- paste(out_names, " <- rep(0, length(all_time))", sep = "")
    eval(parse(text = order))
  }
  order <- paste("out_data <- data.frame(all_time, ", paste_vec(out_names, sep = ", "), ")", sep = "")
  eval(parse(text = order))
  
  for(i in 2:dim(out_data)[2]){
    dates_vec <- data[,dates_name[i - 1]]
    dates_vec <- dates_vec[is.na(dates_vec) == F]
    for(j in 1:dim(out_data)[1]){
      value <- length(grep(x = dates_vec, pattern = paste("^", out_data$all_time[j], sep = "")))
      out_data[j, i] <- value
    }
  }
  return(out_data)
}


date_count2 <- function(data = data.frame(), dates_name = c(), precise = 7, id_var = ""){
  id_pool <- unique(data[,id_var])
  out_data <- create_0_row_df(c("all_time", paste(dates_name,"_num", sep = ""), "type"))
  for(i in 1:length(id_pool)){
    data_temp <- data[data[,id_var] == id_pool[i],]
    result_temp <- date_count(data = data_temp, dates_name = dates_name, precise = precise)
    result_temp$type = id_pool[i]
    out_data <- rbind(out_data, result_temp)
  }
  return(out_data)
}

#### TEST AREA ####

# date1 <- c("2023-01-01", "2023-01-15", "2023-02-02")
# date2 <- c("2023-02-01", "2023-01-15", "2023-02-02")
# date3 <- c("2023-02-01", "2023-03-15", NA)
# data <- data.frame(date1, date2, date3)
# dates_name <- names(data)
# data$zhonglei <- c("a", "b", "b")
# id_var <- "zhonglei"
# 
# date_count(data = data, dates_name = dates_name)
# date_count2(data = data, dates_name = dates_name, id_var = id_var)
